using System;
/* CsJni - .NET / Java Bridge
 * 
 * Copyright 2010 Robert E. Burke Licensed under the Apache License, Version 
 * 2.0 (the "License"); you may not use this file except in compliance with 
 * the License. You may obtain a copy of the License at 
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable 
 * law or agreed to in writing, software distributed under the License is 
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
 * KIND, either express or implied. See the License for the specific language 
 * governing permissions and limitations under the License. 
*/

using System.Collections.Generic;
using System.Text;

namespace CsJni
{
    /// <summary>
    /// A convenience class to load the main class of a Java Program and invoke it.
    /// </summary>
    public sealed class JavaProgramDriver
    {
        private JavaProgramDriver() { }
        
        /// <summary>
        /// Calls the main static method of a given Java class.
        /// NOTE: this method DOES NOT return.  It calls System.Environment.Exit.
        /// If the Java program calls System.exit, this method will also not return.  
        /// The .NET program should end with the same error code as the Java program.
        /// </summary>
        /// <param name="mainClassName">The JNI class name containg the method</param>
        /// <param name="arguments">The arguments to pass to the main method.</param>
        public static void RunMain(string mainClassName, string[] arguments)
        {
            JniEnvironment env = JavaVM.SafeFindEnvironment();
            JniLocalFrame frame = env.CreateLocalFrame(10);
            try
            {
                JniClass mainClass = JniClass.FindClass(env, mainClassName);
                JniMethod method = mainClass.GetStaticMethodId(env, "main", "([Ljava/lang/String;)V");
                JniObjectArray javaArguments = JniString.PackStringArray(env, arguments);
                JValue[] methodArgs = new JValue[1];
                methodArgs[0].AssignObjectValue(javaArguments);
                method.CallStaticVoidMethod(env, methodArgs);
            }
            catch (JniThrowableException ex)
            {
                System.Console.Out.WriteLine(ex.Throwable.ExtractStackTrace(env));
                System.Environment.Exit(1);
                throw;
            }
            catch (Exception ex)
            {
                System.Console.Out.WriteLine(JniThrowable.ExtractDotNetExceptionMessage(ex));
                System.Environment.Exit(1);
                throw;
            }
            finally
            {
                frame.SafePop();
            }
            System.Environment.Exit(0);
        }
    }
}
